const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();

// 首页
app.get('/', (req, res) => {
  const filePath = path.join(__dirname,  'src', 'views', 'index.html');
  res.sendFile(filePath, (err) => {
    if (err) {
      console.error(err);
      res.status(404).send('File not found');
    }
  });
});

// 接口
app.use('/api/:module', (req, res, next) => {
  const moduleName = req.params.module;
  const modulePath = `./src/api/${moduleName}.js`;
  try {
    const module = require(modulePath);
    if (typeof module.get === 'function') {
      app.get(`/api/${moduleName}`, module.get);
    }
    if (typeof module.post === 'function') {
      app.post(`/api/${moduleName}`, module.post);
    }
  } catch (err) {
    console.error(`Failed to load module '${moduleName}':`, err);
  }
  next();
});

// 视图
app.get('/view/:filename', (req, res) => {
  const filename = req.params.filename;
  let filePath = null;
  filePath = path.join(__dirname, 'src', 'views', `${filename}.html`);
  if(filePath !== null){
    res.sendFile(filePath, (err) => {
      if (err) {
        console.error(err);
        res.status(404).send('Not Found');
        return;
      }
    });
  }
});

// 图片
app.get('/img/:filename', (req, res) => {
  const filename = req.params.filename;
  let filePath = null;
  filePath = path.join(__dirname, 'src', 'img', filename);
  if(filePath !== null){
    res.sendFile(filePath, (err) => {
      if (err) {
        console.error(err);
        res.status(404).send('Not Found');
        return;
      }
    });
  }
});

app.get('/user', (req, res) => {
  res.send([
    {
      title: 'serverless framework',
      link: 'https://serverless.com',
    },
  ]);
});

app.get('/user/:id', (req, res) => {
  const id = req.params.id;
  res.send({
    id: id,
    title: 'serverless framework',
    link: 'https://serverless.com',
  });
});

app.get('/404', (req, res) => {
  res.status(404).send('Not found');
});

app.get('/500', (req, res) => {
  res.status(500).send('Server Error');
});

// Error handler
app.use(function (err, req, res, next) {
  console.error(err);
  res.status(500).send('Internal Serverless Error');
});

// Web 类型云函数，只能监听 9000 端口
app.listen(9000, () => {
  console.log(`Server start on http://localhost:9000`);
});
